// qwqScheduledScoreboardTask.java

package qwq.zyu.Scoreboard;

import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Set;

public class qwqScheduledScoreboardTask extends BukkitRunnable {

    private final Plugin plugin;
    private final String scoreboardName;
    private final boolean shouldBroadcast;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");

    public qwqScheduledScoreboardTask(Plugin plugin,
                                      String scoreboardName,
                                      boolean shouldBroadcast
    ) {
        this.plugin = plugin;
        this.scoreboardName = scoreboardName;
        this.shouldBroadcast = shouldBroadcast;
    }

    @Override
    public void run() {
        ScoreboardManager manager = Bukkit.getScoreboardManager();
        Scoreboard mainScoreboard = manager.getMainScoreboard();

        Objective obj = mainScoreboard.getObjective(scoreboardName);
        if (obj == null) {
            Bukkit.getLogger().warning("[qwq_spigot_plugin] Scoreboard not found: " + scoreboardName);
            return;
        }

        Set<String> entries = obj.getScoreboard().getEntries();
        StringBuilder outputSb = new StringBuilder();
        for (String entry : entries) {
            if (entry.startsWith("#")) continue; // 忽略特殊标记条目

            OfflinePlayer player = Bukkit.getOfflinePlayer(entry);
            if (!Objects.equals(player.getName(), entry)) continue; // 检查是否为玩家名称而不是UUID

            Score score = obj.getScore(entry);
            outputSb.append(player.getName()).append(": ").append(score.getScore()).append("\n");
        }

        try {
            writeToFile(outputSb.toString());
        } catch (IOException e) {
            Bukkit.getLogger().severe("[qwq_spigot_plugin] Failed to save scoreboard " + scoreboardName + " to file.");
            e.printStackTrace();
        }
    }

    private void writeToFile(String content) throws IOException {
        File dataFolder = plugin.getDataFolder();
        File scoreboardDir = new File(dataFolder, "scoreboard_loggings/" + scoreboardName);
        if (!scoreboardDir.exists()) {
            scoreboardDir.mkdirs(); // 如果不存在则创建目录
        }

        File file = new File(scoreboardDir, scoreboardName + "_logging.txt");

        // 使用覆盖模式写入文件
        try (FileWriter writer = new FileWriter(file, false)) { // 设置为false表示覆盖模式
            writer.write(dateFormat.format(new Date()) + "\n" + content);
        }

        if (shouldBroadcast){
            // 输出到控制台
            String relativePath = "scoreboard_loggings/" + scoreboardName + "/" + scoreboardName + "_logging.txt";
//        Bukkit.getLogger().info(scoreboardName + " 这个计分板的信息已经写入到 " + relativePath);
            Bukkit.getServer().broadcastMessage(scoreboardName + " 这个计分板的信息已经写入到 " + relativePath);
        }

    }
}